export class DashBoard {
  constructor (canvasId, value, options) {
    this._initParams(canvasId, value, options)
  }

  _initParams (canvasId, value, options) {
    this.canvasDom = document.getElementById(canvasId)
    console.log(this.canvasDom)
    if (!this.canvasDom) {
      return
    }
    this.percent = value || 0
    this.width = this.canvasDom.width
    this.height = this.canvasDom.height
    this.ctx = this.canvasDom.getContext('2d')
    this.radius = this.width / 2
    this.bgColor = 'gray'
    this.activeColor = '#ff5000'
    this.fontSize = '20px microsoft yahei'
    this.fontColor = '#ff5000'
    this.startPosition = 0.75 * Math.PI
    this.endPosition = 2.25 * Math.PI
    this.borderWidth = 16
    this.timer = 20
    if (options) {
      this.bgColor = options.bgColor || this.bgColor
      this.activeColor = options.activeColor || this.activeColor
      this.fontSize = options.fontSize || this.fontSize
      this.fontColor = options.fontColor || this.fontColor
      this.startPosition = (options.startPosition || this.startPosition)
      this.endPosition = (options.endPosition || this.endPosition)
      this.borderWidth = options.borderWidth || this.borderWidth
      this.timer = options.timer || this.timer
    }
    this._init()
  }

  _init () {
    this._initDashBoardBg()
    this._canvasTap(0, this.percent, this.timer, this.width / 2, this.height / 2)
  }

  _initDashBoardBg () {
    console.log(this.startPosition)
    console.log(this.endPosition)
    this.ctx.arc(this.width / 2, this.height / 2, this.radius - this.borderWidth / 2, this.startPosition, this.endPosition);
    this.ctx.strokeStyle = this.bgColor
    this.ctx.lineWidth = this.borderWidth
    this.ctx.lineCap = "round"
    this.ctx.stroke();
  }
  _canvasTap (start, end, time, w, h) {
    var that = this;
    if (start > end) {
      return false;
    }
    this._run(start, w, h);
    start++;
    setTimeout(function () {
      that._canvasTap(start, end, time, w, h);
    }, time);
  }

  _run (c, w, h) {
    // let num = (1.5  * Math.PI / 100 * c) + 0.75 * Math.PI
    let num = (this.endPosition - this.startPosition) / 100 * c + this.startPosition
    this.ctx.beginPath()
    this.ctx.arc(w, h, w - this.borderWidth / 2, this.startPosition, num); //每个间隔绘制的弧度
    this.ctx.strokeStyle = this.activeColor;
    this.ctx.lineWidth = this.borderWidth;
    this.ctx.lineCap = "round"
    this.ctx.stroke();
    this.ctx.clearRect(w / 2, h / 2 ,w, h)
    this.ctx.beginPath();
    this.ctx.font = this.fontSize; //注意不要加引号
    this.ctx.fillStyle = this.fontColor
    this.ctx.textAlign = "center"
    this.ctx.textBaseline = "middle"
    this.ctx.fillText(c + "%", w, h);
  }
}
